package com.by.service.impl;

import com.by.bean.PageBean;
import com.by.bean.ProductInfo;
import com.by.crud.BaseServiceImpl;
import com.by.mapper.ProductInfoMapper;
import com.by.query.ProductInfoQuery;
import com.by.service.ProductInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * date 2025/2/20 16:43
 * author bjj
 * decoration
 * version 1.0
 * since jdk11
 */
@Service
public class ProductInfoServiceImpl extends BaseServiceImpl<ProductInfo, ProductInfoMapper> implements ProductInfoService {

    @Autowired
    ProductInfoMapper productInfoMapper;
    /**
     * 产品信息查询
     * @param productInfoQuery
     * @return
     */
    @Override
    public PageBean query(ProductInfoQuery productInfoQuery) {
        PageHelper.startPage(productInfoQuery.getPage(),productInfoQuery.getPageSize());
        List list =baseMapper.query(productInfoQuery);
        PageInfo pageInfo = new PageInfo(list);
        return new PageBean(productInfoQuery.getPage(),productInfoQuery.getPageSize(),pageInfo.getTotal(),list);
    }

    @Override
    public ProductInfo get(String productId) {
        return productInfoMapper.get(productId);
    }

    //保存产品时根据分类自动生成编码
    @Override
    public int save(ProductInfo productInfo) {
        productInfo.setProductId(getNextId(productInfo.getProductType(),productInfo.getProductCategory()));
        return productInfoMapper.save(productInfo);
    }


    //获取下一个id
    String getNextId(int type,int category){
        // 修改日期格式为4位年份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
        String currentDate = LocalDate.now().format(formatter);
        String maxId = productInfoMapper.getMaxId(type, category);

        if (maxId == null || maxId.length() < 7) {
            // 初始ID格式: 类型+分类+年+001
            return String.format("%d%d%s001", type, category, currentDate);
        } else {
           long max = Long.parseLong(maxId);
           return max+1+"";
        }
    }

}
